#include "../User/BSP/uart.h"

#include "main.h"

#define BUFFER_SIZE (10) /* 缓冲数组大小 */

extern UART_HandleTypeDef huart1;
extern DMA_HandleTypeDef hdma_usart1_rx;
extern DMA_HandleTypeDef hdma_usart1_tx;

struct {
  volatile uint8_t len;
  volatile uint8_t flag;
  uint8_t buffer[BUFFER_SIZE];
} Uart;

void BSP_Uart_Init() {
  __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);
  HAL_UART_Receive_DMA(&huart1, Uart.buffer, BUFFER_SIZE);
}

uint8_t *BSP_Uart_GetDataAddr() { return Uart.buffer; }
uint8_t BSP_Uart_GetDataLen() { return Uart.len; }

uint8_t Uart_SendDMA(uint8_t *buf, uint8_t len) {
  return HAL_UART_Transmit_DMA(&huart1, buf, len);
}

bool BSP_Uart_CheckFlag() {
  if (Uart.flag) {
    Uart.flag = 0;
    BSP_Uart_StartDMA();
    return true;
  } else
    return false;
}

uint8_t BSP_Uart_StartDMA() {
  return HAL_UART_Receive_DMA(&huart1, Uart.buffer, BUFFER_SIZE);
}

void Uart_IRQHandler() {
  if ((__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE) != RESET)) {
    __HAL_UART_CLEAR_IDLEFLAG(&huart1);
    HAL_UART_DMAStop(&huart1);
    Uart.len = BUFFER_SIZE - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx);
    Uart.flag = 1;  // TODO: ThreadFlag
  }
}
